const common = {};

/**
 * 跳转方法判断
 */ function skipWay(options) {
    if (options.url) {
        switch (options.skipWay) {
          case "navigateTo":
            wx.navigateTo({
                url: options.url
            });
            break;

          case "relaunchTo":
            wx.relaunchTo({
                url: options.url
            });
            break;

          case "redireactTo":
            wx.redireactTo({
                url: options.url
            });
            break;

          default:
            wx.navigateTo({
                url: options.url
            });
        }
    }
}

common.getUserInfoNew = (options => {
    console.log("走到老的授权头像");
    if (options && options.success) {
        options.success(wx.getStorageSync("user"));
    }
    skipWay(options);
}), common.getUserProfile = (options => {
    let openid = wx.getStorageSync("user").openid || "";
    wx.getUserProfile({
        desc: "用于完善会员资料",
        success: res => {
            let nickname = res.userInfo.nickName;
            let avatar = res.userInfo.avatarUrl;
            common.request({
                endpoint: "member/save",
                method: "post",
                data: {
                    openid: openid,
                    nickname: res.userInfo.nickName,
                    img: res.userInfo.avatarUrl,
                    gender: res.userInfo.gender
                },
                success: res => {
                    const page = getCurrentPages().pop();
                    const info = page.data.info || {};
                    info.nickname = nickname;
                    info.img = avatar;
                    let user = wx.getStorageSync("user") || {};
                    if (page.data.new_member_audit && page.data.new_member_audit == 1) {
                        //会员审核
                        page.setData({
                            userAuditStatus: 1
                        });
                    } else {
                        //会员免审
                        page.setData({
                            userAuditStatus: 2,
                            info: info,
                            warrant: true
                        });
                        user.warrant = true;
                    }
                    user.nickname = nickname;
                    user.avatar = avatar;
                    wx.setStorage({
                        key: "user",
                        data: user
                    });
                    if (options && options.success) {
                        options.success(user);
                    }
                },
                fail: res => {}
            });
        },
        fail: function() {
            const page = getCurrentPages().pop();
            page.setData({
                showInfoTip: true
            });
        }
    });
});

common.checkUserWarrant = (() => {
    return wx.getStorageSync("user").warrant || false;
})
/** 
 * 统一请求方法: 在请求参数头中包含程序的 appid 和 用户的 openid(如果有)
 * endpoint: string 请求的接口地址
 * method: string 请求的方法
 * data: object 请求的数据
 * success: function 请求成功的方法 回调参数 res.data
 * fail: function 请求失败的方法 回调参数 错误代码和错误参数
 * complete: function 请求完成的方法
 */;

common.request = (options => {
    let app = getApp();
    let openid = wx.getStorageSync("user").openid || "";
    if (options.header && options.header.openid) {
        openid = options.header.openid;
    }
    let domian = app.globalData.domain;
    var un = require("../siteinfo.js");
    let uniacid;
    if (wx.getStorageSync("uniacid")) {
        uniacid = wx.getStorageSync("uniacid");
    } else {
        uniacid = un.uniacid;
    }
    //版本号
        var version = un.version;
    let code;
    if (wx.getStorageSync("code")) {
        code = wx.getStorageSync("code");
    } else {
        code = "";
    }
    wx.showNavigationBarLoading();
    wx.request({
        url: domian + options.endpoint,
        method: options.method ? options.method.toUpperCase() : "GET",
        header: {
            "content-type": options.contentType || "application/json",
            openid: openid,
            uniacid: uniacid,
            code: code,
            version: version
        },
        data: {
            ...options.data
        },
        success: res => {
            if (res.statusCode === 200) {
                if (res.data.code && res.data.code !== 0) {
                    options.fail && options.fail({
                        code: res.data.code,
                        message: res.data.message
                    });
                } else {
                    options.success && options.success(res.data);
                }
            } else {
                options.fail && options.fail({
                    code: res.statusCode,
                    message: res.errMsg
                });
            }
        },
        fail: res => {
            options.fail && options.fail({
                code: 500,
                message: res
            });
        },
        complete: res => {
            options.complete && options.complete(res);
            wx.hideNavigationBarLoading();
        }
    });
});

//处理模块开关
common.getModulesSwich = (features => {
    var modulesSwich = {};
    features.forEach((item, index) => {
        switch (item.id) {
          case 1:
            //红包模块
            modulesSwich.redPacket = item.status;
            break;

          case 2:
            //拼手气红包
            modulesSwich.luckPacket = item.status;
            break;

          case 3:
            //秒杀模块
            modulesSwich.secKill = item.status;
            break;

          case 4:
            //满额立减
            modulesSwich.fullReduce = item.status;
            break;

          case 5:
            //拼团模块
            modulesSwich.group = item.status;
            break;

          case 6:
            //积分签到
            modulesSwich.sign = item.status;
            break;

          case 7:
            //积分商城
            modulesSwich.integrationExchange = item.status;
            break;

          case 8:
            //服务商品
            modulesSwich.serverPro = item.status;
            break;

          case 9:
            //充值模块
            modulesSwich.prepaid = item.status;
            break;

          case 11:
            //充值模块
            modulesSwich.brandManage = item.status;
            break;

          case 16:
            //小程序直播
            modulesSwich.live = item.status;
            break;

          case 17:
            //种草
            modulesSwich.grass = item.status;
            break;

          case 22:
            //专项资金活动
            modulesSwich.specFund = item.status;
            break;

          case 19:
            //付费会员卡
            modulesSwich.memberVip = item.status;
            break;

          case 23:
            //区域合伙人
            modulesSwich.areaLeader = item.status;
            break;

          case 26:
            //消费奖励
            modulesSwich.consumptionAward = item.status;
            break;

          case 25:
            //分销功能
            modulesSwich.distributor = item.status;
            break;

          case 39:
            //骑手配送
            modulesSwich.riderDistribution = item.status;
            break;

          case 40:
            //国际化
            modulesSwich.i18 = item.status;
            break;

          case 42:
            modulesSwich.manghe = item.status;
            break;

          case 35:
            //当面付
            modulesSwich.facePay = item.status;
            break;

          case 48:
            //当面付
            modulesSwich.wwb = item.status;
            break;
        }
    });
    return modulesSwich;
});

//获取属性值
function getProperty(obj) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key) === true) {
            return obj[key];
        }
    }
}

//获取基础设置
common.getAppBase = (() => {
    return new Promise(function(resolve, reject) {
        const page = getCurrentPages().pop();
        page.setData({
            appBase: ""
        });
        common.request({
            endpoint: "set/app_base",
            method: "post",
            data: {},
            success: res => {
                page.setData({
                    appBase: res.extra
                });
                resolve();
            },
            fail: function(res) {
                reject(res);
            }
        });
    });
});

common.getCurrentLocation = (key => {
    return new Promise(function(resolve, reject) {
        const page = getCurrentPages().pop();
        page.setData({
            lat: "",
            lng: ""
        });
        common.location().then(function(val) {
            //如果通过授权，那么直接使用腾讯的微信小程序sdk获取当前定位城市
            wx.request({
                url: "https://apis.map.qq.com/ws/geocoder/v1/?location=" + val.latitude + "," + val.longitude,
                method: "get",
                data: {
                    coord_type: 5,
                    get_poi: 0,
                    output: "json",
                    key: key
                },
                success: function(res) {
                    if (res.data.status == 0) {
                        if (res.data) {
                            page.setData({
                                lat: res.data.result.location.lat,
                                lng: res.data.result.location.lng
                            });
                        }
                    } else {
                        wx.showModal({
                            title: "定位错误",
                            content: res.data.message,
                            showCancel: false,
                            confirmText: "关闭"
                        });
                    }
                    resolve();
                }
            });
        }, function(error) {
            //如果用户拒绝了授权，那么这里会提醒他，去授权后再定位
            wx.showModal({
                title: "",
                content: "自动定位需要授权地理定位选项",
                confirmText: "去授权",
                success(res) {
                    if (res.confirm) {
                        wx.openSetting({
                            success(res) {
                                common.getCurrentLocation(key);
                            }
                        });
                    }
                }
            });
            reject(error);
        });
    });
});

//定位，获取当前经纬度
common.location = (() => {
    return new Promise(function(resolve, reject) {
        wx.getLocation({
            type: "gcj02",
            isHighAccuracy: true,
            // altitude: true,
            success: function(res) {
                resolve(res);
            },
            fail(res) {
                reject(res);
            }
        });
    });
});

//获取购物车最新数量
common.getCart = (() => {
    let goods = wx.getStorageSync("cart");
    let invalid = wx.getStorageSync("invalid") || [];
    let item_idBox = [];
    let items = [];
    let items2 = [];
    const page = getCurrentPages().pop();
    for (var i = 0; i < goods.length; i++) {
        item_idBox.push(goods[i].id);
    }
    for (var i = 0; i < invalid.length; i++) {
        goods.push(invalid[i]);
        item_idBox.push(invalid[i].id);
    }
    common.request({
        endpoint: "product/cart_num",
        method: "post",
        data: {
            data: item_idBox
        },
        success: res => {
            var stock;
            var defaultPro = res.extra.default;
            var express = res.extra.express;
            //处理数据
                        if (defaultPro.length > 0) {
                defaultPro.forEach((item, index) => {
                    item.proType = 0;
                });
            }
            if (express.length > 0) {
                express.forEach((item, index) => {
                    item.proType = 1;
                });
            }
            stock = defaultPro.concat(express);
            for (var i = 0; i < stock.length; i++) {
                if (stock[i].status == 1) {
                    if (stock[i].stock_number > 0) {
                        goods.forEach((a, b) => {
                            // 在有快递配送的时候顺序会变所以不能直接用index来，而是用id来确定商品
                            if (a.id == stock[i].id) {
                                goods[b].stock_number = stock[i].stock_number;
                                goods[b].status == 1;
                                items.push(goods[b]);
                            }
                        });
                    } else {
                        goods.forEach((a, b) => {
                            // 在有快递配送的时候顺序会变所以不能直接用index来，而是用id来确定商品
                            if (a.id == stock[i].id) {
                                items2.push(goods[b]);
                            }
                        });
                    }
                } else {
                    goods.forEach((a, b) => {
                        // 在有快递配送的时候顺序会变所以不能直接用index来，而是用id来确定商品
                        if (a.id == stock[i].id) {
                            goods[b].status = 0;
                            items2.push(goods[b]);
                        }
                    });
                }
            }
            for (var j = 0; j < items.length; j++) {
                items[j]["select"] = 0;
            }
            let cart_count = 0;
            for (var i = 0; i < items.length; i++) {
                cart_count += Number(items[i]["count"]);
            }
            wx.setStorageSync("cart_count", cart_count);
            wx.setStorageSync("cart", items);
            wx.setStorageSync("invalid", items2);
            page.setData({
                cart_count: cart_count
            });
            common.changeIconNum(cart_count, 2);
        }
    });
})
/**
 * 改变购物车上标数字
 */;

common.changeIconNum = ((num, index) => {
    const page = getCurrentPages().pop();
    var tabBarStatus = page.data.tabBarStatus;
    var tabBar = page.data.tabBar;
    if (tabBar && tabBarStatus == 0) {
        tabBar[index].num = num;
        page.setData({
            tabBar: tabBar,
            tabBarStatus: tabBarStatus
        });
    } else if (tabBar && tabBarStatus == 1) {
        tabBar.map(item => {
            if (item.url == "/pages/shopcart/shopcart") {
                item.num = num;
            }
        });
        page.setData({
            tabBar: tabBar,
            tabBarStatus: tabBarStatus,
            num_isShow: true
        });
    }
})
/*函数节流*/;

common.throttle = ((fn, interval) => {
    var enterTime = 0;
    //触发的时间
        var gapTime = interval || 300;
    //间隔时间，如果interval不传，则默认300ms
        return function() {
        wx.stopPullDownRefresh();
        var context = this;
        var backTime = new Date();
        //第一次函数return即触发的时间
                if (backTime - enterTime > gapTime) {
            fn.call(context, arguments);
            enterTime = backTime;
            //赋值给第一次触发的时间，这样就保存了第二次触发的时间
                }
    };
})
/*函数防抖*/;

common.debounce = ((fn, interval) => {
    console.log("进入防抖");
    var timer;
    var gapTime = interval || 1e3;
    //间隔时间，如果interval不传，则默认1000ms
        return function() {
        clearTimeout(timer);
        var context = this;
        var args = arguments;
        //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
                timer = setTimeout(function() {
            fn.call(context, args);
        }, gapTime);
    };
});

common.getBottomIcon = (current => {
    return new Promise(function(resolve, reject) {
        const page = getCurrentPages().pop();
        page.setData({
            num_isShow: false
        });
        common.request({
            endpoint: "set/bottom_icon",
            method: "get",
            data: {},
            success: res => {
                let tabBar = [];
                let tabBarStatus = 0;
                if (res.extra && res.extra.length) {
                    res.extra.map(item => {
                        tabBar.push({
                            id: item.id,
                            iconName: item.icon_text,
                            tip: item.define_name,
                            current: item.link == "/" + page.route || item.link.indexOf(page.route) >= 0 ? 1 : 0,
                            num: 0,
                            url: item.link,
                            style: item.style,
                            status: item.status,
                            selected_icon: item.selected_icon,
                            unselected_icon: item.unselected_icon,
                            unselected_color: item.unselected_color,
                            selected_color: item.selected_color,
                            openType: item.link == "/pages/index/index" || item.link == "/pages/personal/personal" || item.link.indexOf("/pages/classfit/classfit") >= 0 || item.link == "/pages/order/order" ? "switchTab" : "navigate"
                        });
                    });
                    tabBarStatus = 1;
                } else {
                    tabBar = [ {
                        iconName: "icon-shouye1",
                        tip: "首页",
                        current: current == 1 ? 1 : 0,
                        num: 0,
                        url: "/pages/index/index",
                        openType: "switchTab"
                    }, {
                        iconName: "icon-fenlei1",
                        tip: "分类",
                        current: current == 2 ? 1 : 0,
                        num: 0,
                        url: "/pages/classfit/classfit",
                        openType: "switchTab"
                    }, {
                        iconName: "icon-gouwuche2",
                        tip: "购物车",
                        current: current == 3 ? 1 : 0,
                        num: wx.getStorageSync("cart_count"),
                        url: "/pages/shopcart/shopcart"
                    }, {
                        iconName: "icon-dingdan2",
                        tip: "订单",
                        current: current == 4 ? 1 : 0,
                        num: 0,
                        url: "/pages/order/order",
                        openType: "switchTab"
                    }, {
                        iconName: "icon-wode1",
                        tip: "我的",
                        current: current == 5 ? 1 : 0,
                        num: 0,
                        url: "/pages/personal/personal",
                        openType: "switchTab"
                    } ];
                    tabBarStatus = 0;
                }
                page.setData({
                    tabBar: tabBar,
                    tabBarStatus: tabBarStatus
                });
                resolve();
            },
            fail: function(res) {
                reject(res);
            }
        });
    });
});

module.exports.common = common;